import React, { useContext, useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Table, Input, Form, Popconfirm } from 'antd';
import { FormInstance } from 'antd/lib/form';

const EditableContext = React.createContext<FormInstance<any> | null>(null);
//形参类型
interface Item {
  keys: string;
  grade: string;
  range: number;
  epilogue: string;
  id: string;
}

interface EditableRowProps {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  keys: React.ReactNode;
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
  handleDelete: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  keys,
  children,
  dataIndex,
  record,
  handleSave,
  handleDelete,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<Input>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    console.log(record);
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      console.log(values);
      console.log(record);
      if (values.range) {
        record.range = values.range;
      }
      if (values.grade) {
        record.grade = values.grade;
      }
      if (values.epilogue) {
        record.epilogue = values.epilogue;
      }
      toggleEdit();
      handleSave(record);
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `请输入${title} .`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];
interface DataType {
  keys: React.Key;
  jobComplete: boolean;
  grade: string;
  range: number;
  epilogue: string;
  id: string;
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
class EditableTable extends React.Component<any, any> {
  columnLing: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[];
  constructor(props: EditableTableProps) {
    super(props);
    this.columnLing = [
      {
        title: '分数',
        width: 60,
        dataIndex: 'range',
        editable: true,
      },
      {
        title: '等级',
        width: 70,
        dataIndex: 'grade',
        editable: true,
      },
      {
        title: '结语',
        width: 220,
        dataIndex: 'epilogue',
        editable: true,
      },
      {
        title: '操作',
        width: 60,
        dataIndex: 'actions',
        render: (text: any, record: any) => (
          <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record.id)}>
            <a>删除</a>
          </Popconfirm>
        ),
      },
    ];
    this.state = {
      dataSource: [],
      loading: false,
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      visible: false,
      editingKey: '',
    };
  }

  printArea: any = React.createRef();
  componentDidMount() {
    console.log(this.props);
    const { params } = this.props;
    this.query(params);
  }
  query = (id: any) => {
    //接口
    this.setState({ loading: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'Abp/getList',
      payload: { bankNum: id },
      control: 'Edu_Evaluation',
    }).then(() => {
      var resp = this.props.response.result.items;
      this.setState({ dataSource: resp, totalCount: resp.totalCount, loading: false });
    });
  };
  handleDelete = (id: any) => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { id },
        control: 'Edu_Evaluation',
      })
      .then(() => {
        this.query(this.props.params);
      });
  };
  //修改确认编辑框
  handleSave = (row: DataType) => {
    let newData: DataType[] = [];
    const { dataSource } = this.state;
    dataSource.forEach((element: DataType) => {
      if (element.id === row.id) {
        element.range = row.range;
        element.grade = row.grade;
        element.epilogue = row.epilogue;
        newData.push(element);
      }
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'Abp/update',
      payload: { ...newData[0] },
      control: 'Edu_Evaluation',
    }).then(() => {
      this.query(this.props.params);
    });
  };
  render() {
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columnLing.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: (record: DataType) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
          handleDelete: this.handleDelete,
        }),
      };
    });

    return (
      <PageHeaderWrapper title={false}>
        <Table
          rowKey="id"
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns as ColumnTypes}
          scroll={{ x: '800px' }}
          loading={this.state.loading}
        />
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
}))(EditableTable);
